package com.bgds.sys.task;

import cn.hutool.core.collection.CollectionUtil;
import com.bgds.sys.common.pagevo.ElectricMotorVo;
import com.bgds.sys.common.pagevo.RollerAttr;
import com.bgds.sys.common.pagevo.RollerVo;
import com.bgds.sys.common.utils.ResultUtil;
import com.bgds.sys.influx.service.InfluxService;
import com.bgds.sys.module.entity.AlarmLog;
import com.bgds.sys.module.entity.Device;
import com.bgds.sys.module.entity.DeviceDynamicAttr;
import com.bgds.sys.module.service.IAlarmLogService;
import com.bgds.sys.module.service.IDeviceDynamicAttrService;
import com.bgds.sys.module.service.IDeviceService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 辊道监测任务
 * @Author lj
 * @create: 2020-09-04 15:28
 */
@Slf4j
@Component
public class RollerJob implements Job {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceDynamicAttrService deviceDynamicAttrService;
    @Autowired
    private InfluxService influxService;
    @Autowired
    private IAlarmLogService alarmLogService;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        String deviceCode=dataMap.get("deviceCode").toString();
        List<RollerVo> data=getRollerMessage(deviceCode);
        String id=dataMap.get("id").toString();
        messagingTemplate.convertAndSendToUser(id,"/roller",new ResultUtil<>().setData(data));
    }

    /**
     * 获取辊道段数据
     * @param deviceCode
     * @return
     */
    public List<RollerVo> getRollerMessage(String deviceCode){
       List<Device> devices= deviceService.listByParentCode(deviceCode);
       List<RollerVo> list=new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#.00");
       for(Device device:devices){
           RollerVo rollerVo=new RollerVo();
           rollerVo.setTitle(device.getName());
           rollerVo.setDeviceCode(device.getDeviceCode());
           List<DeviceDynamicAttr> speedElectAttrs=deviceDynamicAttrService.listByDeviceCode(device.getDeviceCode(),"speed_elect");
           //辊道段下的辊轮
           List<DeviceDynamicAttr> currAttrs=deviceDynamicAttrService.listByDeviceCode(device.getDeviceCode(),"curr");
           //influxDB 获取数据
           if(speedElectAttrs.size()>0){
               List<Map<String,Object>> valueMap=influxService.queryByForMap(speedElectAttrs.get(0).getDeviceCode(),speedElectAttrs);
               if(valueMap.size()>0){
                   Map<String,Object> map=valueMap.get(0);
                   //通过日志判断是否异常
                   Integer state=alarmLogService.decideDeviceLevel(device.getDeviceCode());
                   rollerVo.setState(state);
                   RollerAttr rollerAttr=new RollerAttr();
                   rollerAttr.setCf(Float.valueOf(df.format(Float.valueOf(String.valueOf(map.get("current_feedback"))))));
                   rollerAttr.setVf(Float.valueOf(df.format(Float.valueOf(String.valueOf(map.get("speed_feedback"))))));
                   rollerAttr.setVs(Float.valueOf(df.format(Float.valueOf(String.valueOf(map.get("speed_given"))))));
                   Integer num= count(currAttrs);
                   rollerAttr.setAlerts(num);
                   rollerAttr.setTotal(currAttrs.size()==0?1:currAttrs.size());
                   rollerVo.setAttrs(rollerAttr);
                   list.add(rollerVo);
               }
           }
       }
       return list;
    }


    /**
     * 统计辊道段下滚轮的日志
     * @param attrs
     */
    private Integer count( List<DeviceDynamicAttr> attrs){
        Integer num=0;

        if(CollectionUtil.isNotEmpty(attrs)){
            List<Long> ids=  attrs.stream().map(e -> e.getId()).collect(Collectors.toList());
            List<AlarmLog> logs=  alarmLogService.findBatchByAttrIds(ids);
            if(CollectionUtil.isNotEmpty(logs)){
                for(DeviceDynamicAttr attr:attrs){
                    Optional<AlarmLog> optional= logs.stream().filter(log->log.getAttrId().equals(attr.getId())).findFirst();
                    if (optional.isPresent()){
                        num++;
                    }
                }
            }
        }
        return num;
    }

}
